import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

import storage from '@/utils/storage';
import userApi from '../api/user'

export default new Vuex.Store({
  state: {
    token: storage.getToken() ? storage.getToken() : '',
    userInfo: storage.getUserInfo() ? storage.getUserInfo() : '',
  },
  mutations: {
    setToken(state, token) {
      state.token = token,
        storage.setToken(token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo,
        storage.setUserInfo(userInfo)
    },
    removeState(state) {
      state.token = '',
      state.userInfo = '',
      storage.removeTokenAndUserInfo()
    }
  },
  actions: {
    doLogin({ commit }, formName) {
      return new Promise((resolve, reject) => {
        userApi.doLogin(formName.username, formName.password).then(response => {
          if (response.data.flag) {
            let token = response.data.data.token
            commit('setToken', token)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        userApi.getUserInfo().then(response => {
          if(response.data.flag){
            let userInfo = response.data.data
            commit('setUserInfo',userInfo)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    goBack({commit}) {
      return new Promise((resolve,reject)=>{
        userApi.goBack().then(response=>{
          if(response.data.flag){
            commit('removeState')
          }
          resolve(response)
        }).catch(error=>{
          reject(error)
        })
      })
    }
  },
  modules: {

  },
});
